package com.nice.tcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;

import com.nice.controller.MessageDispatch;
import com.nice.message.Message;
import com.nice.message.MessageHandler;

public class NettyMsgHandler extends SimpleChannelInboundHandler<Message>
		implements MessageHandler {

	private int clientId;
	private ChannelHandlerContext ctx;
	private MessageDispatch msgCenter = MessageDispatch.getInstance();

	@Override
	protected void messageReceived(final ChannelHandlerContext ctx, Message msg)
			throws Exception {
		this.ctx = ctx;
		msg.sender = this;
		msgCenter.dispatch(msg);
	}

	@Override
	public void close(ChannelHandlerContext ctx, ChannelPromise promise)
			throws Exception {
		msgCenter.remove(clientId);
		super.close(ctx, promise);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		msgCenter.remove(clientId);
		super.exceptionCaught(ctx, cause);
	}

	@Override
	public void handle(Message msg) {
		ctx.writeAndFlush(msg.toByte());
	}

	@Override
	public void doExit(Message exitMsg) {
		msgCenter.remove(clientId);
	}

}
